﻿using iTool.SQL.Analysis.ColumnRef;
using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;
using System.Text;

namespace iTool.SQL.Analysis.Common
{
    public class SqlBuiltinScalarFunctionCallAnalysis : SqlAnalysisBase
    {
        public SqlBuiltinScalarFunctionCallAnalysis(SqlAnalysisContext context) : base(context)
        {
        }
        // 自定义函数？
        public override void Analysis()
        {
            //StringBuilder where = base.GetWhereBuilder();
            var builtin = (SqlBuiltinScalarFunctionCallExpression)base.CodeObject;
            var where = (WhereOptions)base.WhereOptions;
            switch (builtin.FunctionName)
            {
                // 走索引 (这里不应该 拼接上去)
                case "search":
                    var searchIndex = new SearchIndexOptions();
                    if (where.Left == null)
                        where.Left = searchIndex;
                    else if (where.Right == null)
                        where.Right = searchIndex;

                    //where.Append(builtin.FunctionName);
                    //where.Append('(');
                    base.Next(
                        beforeAction: (index, code, analysis) => code is SqlColumnRefExpression || code is SqlScalarRefExpression,
                        afterAction: (index, _, analysis) =>
                        {
                            //where.Append(',');
                        }, whereProperty: searchIndex);
                    //where[^1] = ')';
                    break;
                default:
                    base.context.Errors.Add("not support:"+base.CodeObject.Sql);
                    break;
            }
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
